package cn.edu.hit;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Deprecated
public class HttpRequestor2 extends HttpRequestor {
    static Logger logger = LoggerFactory.getLogger(HttpRequestor2.class);

    public static class Token {
        String token;
        long aquireTimestamp;
        long expiresIn;
        String refreshToken;

        public Token() {
        }

        public Token(String token, long expiresIn, String refreshToken) {
            this.token = token;
            this.expiresIn = expiresIn * 1000;
            this.refreshToken = refreshToken;
            this.aquireTimestamp = System.currentTimeMillis();
        }

        public boolean isValid() {
            return System.currentTimeMillis() < aquireTimestamp + expiresIn;
        }

        @Override
        public String toString() {
            return "Token{" +
                    "token='" + token + '\'' +
                    ", aquireTimestamp=" + aquireTimestamp +
                    ", expiresIn=" + expiresIn +
                    ", refreshToken='" + refreshToken + '\'' +
                    '}';
        }
    }

    public Token aquireToken(String url, String username, String password) throws Exception {
        JSONObject json = new JSONObject();
        json.put("username", username);
        json.put("password", password);
        logger.info("get the token ,url:" + url + "json:" + json.toString());

        String result = doPost(url, json.toString(), defaultJsonHeaders);
        logger.info("the token:{}", result);
        return getTokenFromJson(result);
    }

    private Token getTokenFromJson(String jsonBody) {
        JSONObject json = JSONObject.fromObject(jsonBody);
        String tokenString = json.getString("access_token");
        String refreshToken = json.getString("refresh_token");
        long expire = json.getLong("expires_in");
        return new Token(tokenString, expire, refreshToken);
    }

    public Token refreshToken(String url, Token oldToken) throws Exception {
        String result = doPost(url + oldToken.refreshToken, "");
        return getTokenFromJson(result);
    }

    public static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    public String getFeatures(String url, Token token, String module, long fromTime, long endTime, boolean sort, String... ports) throws Exception {
        JSONObject json = new JSONObject();
//        json.put("thingId",module);
        json.put("fields", ports);
        json.put("startTime", formatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(fromTime), ZoneId.systemDefault())));
        json.put("endTime", formatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault())));
//        json.put("startTime","20200102143552");
//        json.put("endTime","20200102144552");
        json.put("dataStyle", "row");
//        json.put("timeFormat","");
//        json.put("sort",sort?"asc":"desc");
        logger.info("测点信息请求体:{}", json);
//        String result = doPost(url,json.toString(),headers(defaultJsonHeaders,"Authorization","Bearer "+token.token));
        String result = doPost(url, json.toString(), headers(defaultJsonHeaders));
        return result;
    }

    public String putResults(String url, Token token, List<Map.Entry<Long, String>> faults) throws Exception {
        JSONObject json = new JSONObject();
        json.put("rows", faults.stream().map(entry -> {
            JSONObject row = new JSONObject();
            row.put("time", formatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(entry.getKey()), ZoneId.systemDefault())));
            row.put("fields", Collections.singletonMap("fault", entry.getValue()));
            return row;
        }).collect(Collectors.toList()));
        logger.info("发送故障信息:{}", json);
        String result = doPost(url, json.toString(), headers(defaultJsonHeaders, "Authorization", "Bearer " + token.token));
        logger.info("故障发送确认信息:{}", result);
        return result;
    }

    public String doPost(String url, Token token, String jsonContext) throws Exception {
        return super.doPost(url, jsonContext.toString(), headers(defaultJsonHeaders, "Authorization", "Bearer " + token.token));
    }

    public static void main(String[] args) throws Exception {
        HttpRequestor2 requestor = new HttpRequestor2();
        Token token = requestor.aquireToken("http://222.171.52.120:11185/api/v1/authorization/auth", "wangrp", "Wrp123456");

        System.out.println(token);
        while (true) {
            if (token.isValid()) {
//            token = requestor.refreshToken("http://222.171.52.120:11185/api/v1/authorization/refresh/",token);
//            System.out.println(token);
                System.out.println("token合法");
                String data = requestor.getFeatures(
                        "http://222.171.52.120:11209/api/v1/app/inference",
                        token,
                        "TPMotorInference",
                        System.currentTimeMillis() - 3600000,
                        System.currentTimeMillis(),
                        true,
                        "GEN03001", "GEN03002");
                System.out.println(data);
            } else {
                Token token2 = requestor.refreshToken("http://222.171.52.120:11185/api/v1/authorization/refresh/", token);
                System.out.println("更新token");
                System.out.println(token2.toString());
                String data = requestor.getFeatures(
                        "http://222.171.52.120:11209/api/v1/app/inference",
                        token,
                        "TPMotorInference",
                        System.currentTimeMillis() - 3600,
                        System.currentTimeMillis(),
                        true,
                        "GEN03001", "GEN03002");
                System.out.println(data);
                token = token2;
            }

        }
    }
}
